<?php

namespace App\Http\Model;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;


class GiftBagRechargeLog extends Base
{
    protected $table = 'gift_bag_recharge_log';

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    //查看用户赠送记录
    public function userGiftBagLog($user_id)
    {
        $w['user_id'] = $user_id;
        $date[] = date('Y-m-d 00:00:00', time());
        $date[] = date('Y-m-d 23:59:59', time());
        $w['status'] = 1;
        $res = DB::table($this->table)->where($w)
            ->whereBetween('created_at', $date)
            ->orderBy('rank', 'asc')
            ->get();
        if (!$res) {
            return false;
        }
        return json_decode($res, true);
    }

    //添加赠送记录
    public function createLog($user_id, $rank, $diamond_num, $pearl_rand)
    {
        $data['user_id'] = $user_id;
        $data['rank'] = $rank;
        $data['diamond'] = $diamond_num;
        $data['award_pearl'] = $pearl_rand;
        $data['status'] = 0;
        $data['created_at'] = $data['updated_at'] = date_ymd();
        $res = DB::table($this->table)->insertGetId($data);
        return $res;
    }

    public function updateLog($user_id, $rank, $award_pearl)
    {
        $data['user_id'] = $user_id;
        $data['pearl_num'] = $award_pearl;
        $data['msg'] = '充值礼包奖励金豆';
        $pearl_api = json_decode(curl_request(env('KK_API_HOST') . '/finance/pearl/recharge', $data), true);
        if ($pearl_api['code'] !== 0) {
            //充值失败
            write_log('giftBagRechargeApi', 'pearlApiError', json_encode($data));
            return false;
        }
        $w['user_id'] = $user_id;
        $w['rank'] = $rank;
        $date[] = date('Y-m-d 00:00:00', time());
        $date[] = date('Y-m-d 23:59:59', time());
        return DB::table($this->table)->where($w)
            ->whereBetween('created_at', $date)
            ->update(['status' => 1]);

    }

    /*
     * 查看当天是否领取
     * */
    public function dayLog($user_id, $rank)
    {
        $w['user_id'] = $user_id;
        $w['rank'] = $rank;
        $date[] = date('Y-m-d 00:00:00', time());
        $date[] = date('Y-m-d 23:59:59', time());
        $res = DB::table($this->table)->where($w)
            ->whereBetween('created_at', $date)
            ->first();
        return $res;
    }
}